import React, { useState, forwardRef, useRef, useEffect } from 'react';
import { Form, Modal, Icon, Row, Col } from 'antd';

import { isSuccess } from '@/utils/request';
import If from '@/components/If';

import NumberInput from '@/pages/SalaryManage/components/NumberInput';
import ValidateFormTable from '@/pages/SalaryManage/utils/validateFormTable'

import { querySalaryItemsTree } from '@/services/salaryManage/salaryChart';

import CustomPopover from '../component/CustomPopover';
import SalaryItemsSelect from '../component/SalaryItemsSelect';


import styles from '../style.less'

const rulesMap = {
    salaryItemId: [{
        required: true,
        msg: '请选择'
    }, {
        repeat: true,
        msg: '薪资项类型重复，请修改'
    }],
    referenceValueMin: [
        {
            required: true,
            msg: '请输入参考值'
        },
        {
            type: 'number',
            min: 0,
            msg: '参考值不能小于0'
        }
    ]
}

const customFormTable = new ValidateFormTable(rulesMap)

const generateData = () => ({
    judgeType: 1,
    referenceValueMax: undefined,
    referenceValueMin: undefined,
    salaryItemId: undefined,
    key: `special_${new Date().getTime()}_${Math.floor(Math.random() * 100000)}`,
    rules: customFormTable.initRulesFn()
})


// 设置子模块
const SettingItems = forwardRef(({ salaryItemList, organizationCode, salaryBodyRef, changeHandle }) => {
    const handleFn = (index, key, value) => {
        changeHandle('edit', index, key, value)
    }
    const delList = index => {
        changeHandle('del', index)
    }
    const addList = () => {
        changeHandle('add')
    }

    const [salaryItemTreeList, setSalaryItemTreeList] = useState([])

    useEffect(() => {
        const initFn = async () => {
            const request = await querySalaryItemsTree({
                organizationCode,
                itemType: 2,
                extraType: 0
            })
            if (isSuccess(request)) {
                setSalaryItemTreeList(request.data)
            }
        }
        initFn()

        return () => {
            setSalaryItemTreeList([])
        }
    }, [])

    return (
        <div className={styles.useSalaryItemBox}>
            <Row>
                <Col span={12} >&nbsp;&nbsp;薪资项<CustomPopover content="只针对子级薪资项对比，上级薪资不参与对比" /></Col>
                <Col span={8} >&nbsp;&nbsp;参考值</Col>
                <Col span={4} ></Col>
            </Row>

            <div style={{ maxHeight: 300, overflowY: 'auto', paddingRight: 80 }} ref={salaryBodyRef}>
                <div>
                    {
                        salaryItemList?.map((item, index) => (
                            <Row key={item.key}>
                                <Col span={12} >
                                    <Form.Item
                                        validateStatus={item.rules?.salaryItemId?.validateStatus}
                                        help={item.rules?.salaryItemId?.help}>
                                        <SalaryItemsSelect
                                            itemType={2}
                                            style={{ width: 155 }}
                                            organizationCode={organizationCode}
                                            onChange={v => handleFn(index, 'salaryItemId', v)}
                                            value={item.salaryItemId}
                                            isOwnTree
                                            selectArr={salaryItemTreeList}
                                        />

                                    </Form.Item>
                                </Col>
                                <Col span={8} >
                                    <Form.Item
                                        validateStatus={item.rules?.referenceValueMin?.validateStatus}
                                        help={item.rules?.referenceValueMin?.help}>
                                        <NumberInput
                                            value={item.referenceValueMin}
                                            onChange={v => handleFn(index, 'referenceValueMin', v)}
                                            decimalPlaces={2}
                                            placeholder="请输入"
                                            suffix="%" />
                                    </Form.Item>
                                </Col>
                                <Col span={4} >
                                    {
                                        salaryItemList.length === 1 ? null : <Icon className={styles.delBtn} onClick={() => delList(index)} type="minus-circle" />
                                    }
                                </Col>
                            </Row>

                        ))
                    }
                </div>
            </div>
            <div style={{ paddingRight: 80 }}>
                {
                    salaryItemList.length >= 10 ? null : <Row>
                        <Col span={20} >
                            <div className={styles.addMoreBtn} onClick={() => addList()}>+添加</div>
                        </Col>
                        <Col span={4} ></Col>
                    </Row>
                }
            </div>
        </div>
    )
})

const SalaryItemsSettingModal = Form.create()(({
    visible,
    onOk,
    onCancel,
    salaryItemList,
    salaryBodyRef,
    changeHandle,
    organizationCode }) => (
        <Modal
            title="薪资项参考值设置"
            visible={visible}
            okText="确定"
            onOk={onOk}
            cancelText="取消"
            onCancel={onCancel}
        >
            <SettingItems
                organizationCode={organizationCode}
                salaryItemList={salaryItemList}
                salaryBodyRef={salaryBodyRef}
                changeHandle={changeHandle} />
        </Modal>
    ));
SalaryItemsSettingModal.displayName = 'SalaryItemsSettingModal';

/**
 *总览配置
 * @param organizationCode
 * @param globalInfo
 * @param changeFn
 */
const useSalaryItemsSetting = (salaryItemInfoList = [], organizationCode, changeFn) => {
    // 显示分配
    const [showSalaryItemsSetting, setShowSalaryItemsSetting] = useState(false);
    const [salaryItemList, setSalaryItemList] = useState([]);

    const salaryBodyRef = useRef(null)

    // 展示弹窗
    const onShowSalaryItemsSetting = () => {
        setSalaryItemList(
            salaryItemInfoList.length === 0 ?
                ([generateData()]) :
                JSON.parse(JSON.stringify(salaryItemInfoList)).map(item => ({ ...generateData(), ...item })));
        setShowSalaryItemsSetting(true);
    };

    const scrollTopFn = (element, errData) => {
        const { clientHeight, firstChild } = element.current
        if (clientHeight < firstChild.clientHeight) {
            const num = customFormTable.validateFirstNumFn(errData)
            element.current.scrollTop = num * 65
        }
    }

    // 保存按钮
    const onTotalSetting = () => {
        customFormTable.validateMessageFn(salaryItemList, async (err, data) => {
            console.log(err, salaryBodyRef, data)
            if (err) {
                scrollTopFn(salaryBodyRef, data)
                setSalaryItemList(data)
                return
            }

            const configData = salaryItemList.map(({
                judgeType,
                referenceValueMax,
                referenceValueMin,
                salaryItemId }) => ({
                judgeType,
                referenceValueMax,
                referenceValueMin,
                salaryItemId
            }))
            changeFn(configData)
            setShowSalaryItemsSetting(false)
        })
    };

    // 切换checkbox
    const changeHandle = (type, index, key, value) => {
        switch (type) {
            case 'add':
                setSalaryItemList([...salaryItemList, generateData()])
                break;
            case 'del':
                // eslint-disable-next-line no-case-declarations
                const list = salaryItemList.slice();
                list.splice(index, 1)

                setSalaryItemList(customFormTable.validateRepeatFn(list))
                break;
            default:
                // eslint-disable-next-line no-case-declarations
                const handleObj = salaryItemList[index]
                handleObj[key] = value
                // eslint-disable-next-line no-case-declarations
                const ruleMsg = customFormTable.ruleValidateMsg(key, value)
                handleObj.rules[key] = ruleMsg
                setSalaryItemList(
                    customFormTable.validateRepeatFn([
                        ...salaryItemList.slice(0, index),
                        handleObj,
                        ...salaryItemList.slice(index + 1)])
                )
                break;
        }
    }

    return {
        onShowSalaryItemsSetting,
        render() {
            return (
                <>
                    <If condition={showSalaryItemsSetting}>
                        <SalaryItemsSettingModal
                            visible={showSalaryItemsSetting}
                            onOk={onTotalSetting}
                            organizationCode={organizationCode}
                            onCancel={() => setShowSalaryItemsSetting(false)}
                            changeHandle={changeHandle}
                            salaryBodyRef={salaryBodyRef}
                            salaryItemList={salaryItemList}
                        />
                    </If>
                </>
            );
        }
    };
};

export default useSalaryItemsSetting;
